package com.powerbank.admin.config;

import com.powerbank.admin.service.AdminAuthService;
import com.powerbank.common.exception.BusinessException;
import com.powerbank.common.result.ResultCode;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
 * 管理后台权限拦截器
 */
@Slf4j
@Component
public class AdminAuthInterceptor implements HandlerInterceptor {

    @Autowired
    private AdminAuthService adminAuthService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String requestURI = request.getRequestURI();
        
        // 放行登录和公共接口
        if (requestURI.contains("/auth/login") || 
            requestURI.contains("/auth/logout") ||
            requestURI.contains("/health") ||
            requestURI.contains("/swagger") ||
            requestURI.contains("/doc")) {
            return true;
        }

        // 获取Token
        String token = request.getHeader("Authorization");
        if (token == null || token.trim().isEmpty()) {
            throw new BusinessException(ResultCode.TOKEN_MISSING);
        }

        try {
            // 验证Token并获取管理员ID
            Long adminId = adminAuthService.validateTokenAndGetAdminId(token);
            
            // 将管理员ID设置到请求属性中，供后续使用
            request.setAttribute("adminId", adminId);
            
            log.debug("管理员{}访问接口: {}", adminId, requestURI);
            return true;
            
        } catch (Exception e) {
            log.error("Token验证失败: {}", e.getMessage());
            throw new BusinessException(ResultCode.TOKEN_INVALID);
        }
    }
}